import time
from selenium.webdriver.common.by import By
from selenium.webdriver import Edge
import json
from selenium.webdriver.edge import webdriver


def get_user_id(name):
    option = webdriver.Options()
    option.add_argument("--window-size=1,1")
    browser = Edge(options=option)
    browser.set_window_size(0, 1)
    browser.get('https://www.douyin.com/search/' + name + '?type=user')
    # 使用cookies，免登录
    with open("D:\EdgeDownload\cookies.txt", 'r', encoding='utf8') as f:
        listCookies = json.loads(f.read())
    for cookie in listCookies:
        cookie_dict = {
            # 这个domain看cookies第一个字段就知道了，需要找到并填入
            'domain': '.douyin.com',
            'name': cookie.get('name'),
            'value': cookie.get('value'),
            "expires": '',
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False
        }
        browser.add_cookie(cookie_dict)
        # browser.refresh()  # 刷新网页,cookies才成功
    browser.get('https://www.douyin.com/search/' + name + '?type=user')
    time.sleep(2)

    user_id = (browser.find_element(By.CLASS_NAME, "search-result-card")
               .find_element(By.TAG_NAME, "a").get_attribute('href'))
    print(user_id[28:].split('?')[0])
    return user_id[28:].split('?')[0]


def get_video_arr(user_id):
    # 设置隐藏浏览器
    option = webdriver.Options()
    option.add_argument('--headless')
    browser = Edge(options=option)
    browser.set_window_size(0, 1)
    browser.get("https://www.douyin.com/user/" + user_id)

    # 使用cookies，免登录
    with open("D:\EdgeDownload\cookies.txt", 'r', encoding='utf8') as f:
        listCookies = json.loads(f.read())
    for cookie in listCookies:
        cookie_dict = {
            # 这个domain看cookies第一个字段就知道了，需要找到并填入
            'domain': '.douyin.com',
            'name': cookie.get('name'),
            'value': cookie.get('value'),
            "expires": '',
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False
        }
        browser.add_cookie(cookie_dict)
        # browser.refresh()  # 刷新网页,cookies才成功

    browser.get("https://www.douyin.com/user/" + user_id)
    time.sleep(2)
    li_list = (browser.find_element(By.CLASS_NAME, "LPv6KBIL")
               .find_element(By.TAG_NAME, "ul")
               .find_elements(By.TAG_NAME, "li"))
    result = []
    for li in li_list:
        x = li.find_element(By.TAG_NAME, "div").find_element(By.TAG_NAME, "a").get_attribute('href')
        print(x[29:])
        result.append(x[29:])
    return result


get_video_arr(get_user_id("宋亚轩"))
